package com.rivercloud.controller;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.mvc.view.JspView;

import com.alibaba.fastjson.JSON;
import com.rivercloud.dao.ExcelDAO;
import com.rivercloud.dao.MergeDao;
import com.rivercloud.dao.MergeRowDao;
import com.rivercloud.dao.ProjectDao;
import com.rivercloud.dao.TableColDao;
import com.rivercloud.dao.TableDao;
import com.rivercloud.dao.TableRowDao;
import com.rivercloud.dao.UserDao;
import com.rivercloud.dao.UserProjectDao;
import com.rivercloud.dao.Impl.MergeDaoImpl;
import com.rivercloud.dao.Impl.MergeRowDaoImpl;
import com.rivercloud.dao.Impl.ProjectDaoImpl;
import com.rivercloud.dao.Impl.TableColDaoImpl;
import com.rivercloud.dao.Impl.TableDaoImpl;
import com.rivercloud.dao.Impl.TableRowDaoImpl;
import com.rivercloud.dao.Impl.UserDaoImpl;
import com.rivercloud.dao.Impl.UserProjectDaoImpl;
import com.rivercloud.entity.ExcelTable;
import com.rivercloud.entity.Merge;
import com.rivercloud.entity.MergeRow;
import com.rivercloud.entity.TableCol;
import com.rivercloud.entity.TableRow;
import com.rivercloud.entity.User;
@Filters(@By(type=CheckSession.class, args={"user", "/login.jsp"}))  
@At("/table")
@Fail("http:500")
public class ExcelTableController {
	@Inject
	private ExcelDAO excelDAO = new ExcelDAO();
	@Inject
	private TableDao tableDao = new TableDaoImpl();
	@Inject
	private TableColDao tableColDao = new TableColDaoImpl();
	private TableRowDao tableRowDao = new TableRowDaoImpl();
	private ProjectDao projectDao = new ProjectDaoImpl();
	private UserDao userdao = new UserDaoImpl();
	private MergeDao mergeDao = new MergeDaoImpl();
	private MergeRowDao mergeRowDao = new MergeRowDaoImpl();
	private UserProjectDao userProjectDao = new UserProjectDaoImpl();

	@At("/createTable2")
	
	public void createTemplate2(HttpServletRequest request,HttpServletResponse response) {
		

		ExcelTable excelTable = new ExcelTable();
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		int userId = Integer.parseInt(request.getParameter("userId"));
		User user = userdao.findUserById(userId);
		
		String tableName = request.getParameter("tableName");
		
		int totalNumber = Integer.parseInt(request.getParameter("totalNumber"));
		
		Map<String, String[]> map = request.getParameterMap();
		System.out.println(map.size());
		
		
		
		try {
			List<TableCol> tableColList = new ArrayList<>();
			Class c = TableCol.class;
			Field[] fields = c.getDeclaredFields();
			Field.setAccessible(fields, true);
			excelTable.setTableName(tableName);
			excelTable.setProjectId(projectId);
			excelTable.setUserId(userId);
			excelTable.setCreator(user.getName());
			
			tableDao.addTable(excelTable);
			int tableId = tableDao.lastInsertId();
			
			for (int i = 0; i < totalNumber ; i++) {
				TableCol tableCol = new TableCol();
				tableCol.setColNum(i + 1);
				tableCol.setTableId(tableId);
				int flag = 0;
				for (int j = 0; j < fields.length; j++) {
					Field field = fields[j];
					String name = field.getName();
					if (!name.equals("createTime")) {
						Constructor<?> constructor = field.getType().getConstructor(String.class);
						String parameter = request.getParameter(name + (i + 1));
						if (parameter != null && !"".equals(parameter)) {
							if(name.equals("colEditor")){
								flag++; 
								System.out.println(parameter);
								String colEditor = userdao.findIdByName(parameter)+"";
								field.set(tableCol, constructor.newInstance(colEditor));
							}else{
								
									flag++;
									field.set(tableCol, constructor.newInstance(parameter));
							}	
						}
					}
				}
				if (flag != 0) {
					
					tableColList.add(tableCol);
					tableColDao.addTableCol(tableCol);
				}
				
				
				
			}
			
			String num = request.getParameter("rowNum");
			if(num != null){
				
				int rowNum = Integer.parseInt(num);
				for (int i = 0; i < rowNum; i++) {
					TableRow tableRow = new TableRow();
					String edt = request.getParameter("editor"+(i+1));
					if(edt != null){
						
						
						int editor = userdao.findIdByName(edt);
						tableRow.setUserId(editor);
					}
					tableRow.setTableId(tableId);
					tableRowDao.addTableRow(tableRow);
				}
			}
			System.out.println(tableColList.size());
			
			response.getWriter().print(tableId);
			request.setAttribute("tableId", tableId);
			request.setAttribute("excelTable", excelTable);
			request.setAttribute("tableColList", tableColList);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@At("/createTable")
	@Ok("jsp:jsp.tableInfo")
	public void createTemplate(HttpServletRequest request) {

		ExcelTable excelTable = new ExcelTable();
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		int userId = Integer.parseInt(request.getParameter("userId"));
		User user = userdao.findUserById(userId);

		String tableName = request.getParameter("tableName");

		Map<String, String[]> map = request.getParameterMap();
		System.out.println(map.size());

		try {
			List<TableCol> tableColList = new ArrayList<>();
			Class c = TableCol.class;
			Field[] fields = c.getDeclaredFields();
			Field.setAccessible(fields, true);
			excelTable.setTableName(tableName);
			excelTable.setProjectId(projectId);
			excelTable.setUserId(userId);
			excelTable.setCreator(user.getName());

			tableDao.addTable(excelTable);
			int tableId = tableDao.findIdByTableName(tableName);
			int tableId2 = tableDao.lastInsertId();
			for (int i = 0; i < (map.size() - 1) / 3; i++) {
				TableCol tableCol = new TableCol();
				tableCol.setColNum(i + 1);
				tableCol.setTableId(tableId);
				int flag = 0;
				for (int j = 0; j < fields.length; j++) {
					Field field = fields[j];
					String name = field.getName();
					if (!name.equals("createTime")) {
						Constructor<?> constructor = field.getType().getConstructor(String.class);
						String parameter = request.getParameter(name + (i + 1));
						if (parameter != null && !"".equals(parameter)) {
							flag++;
							field.set(tableCol, constructor.newInstance(parameter));
						}
					}
				}
				if (flag != 0) {

					tableColList.add(tableCol);
					tableColDao.addTableCol(tableCol);
				}
			}
			String num = request.getParameter("rowNum");
			if(num != null){
				
				int rowNum = Integer.parseInt(num);
				for (int i = 0; i < rowNum; i++) {
					TableRow tableRow = new TableRow();
					String edt = request.getParameter("editor"+(i+1));
					if(edt != null){
						
						int editor = Integer.parseInt(edt);
						tableRow.setTableId(tableId);
						tableRow.setUserId(editor);
					}
					tableRowDao.addTableRow(tableRow);
				}
			}
			
			
			
			
			System.out.println(tableColList.size());
			request.setAttribute("excelTable", excelTable);
			request.setAttribute("tableColList", tableColList);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//检验表格名是否可用
	@At("/checkTableName")

	public void checkTableName(HttpServletRequest request,HttpServletResponse response) {
		try {
			String tableName = request.getParameter("tableName");
			ExcelTable existTable  = tableDao.checkTableName(tableName);
			if(existTable == null){
				response.getWriter().print("1");
			}else{
				response.getWriter().print("2");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	
	@At("/tableInfo")
	@Ok("jsp:jsp.tableInfo")
	public void template(HttpServletRequest request){
		int tableId = Integer.parseInt(request.getParameter("tableId"));
		ExcelTable excelTable = tableDao.findTableById(tableId);
		List<TableCol> tableColList = 
				tableColDao.findByTableId(tableId);
		
		request.setAttribute("excelTable", excelTable);
		request.setAttribute("tableColList", tableColList);
	}

	
	@At("/tableList")
	@Ok("jsp:jsp.tableList")
	public View templateList(HttpServletRequest request) {
		String pid = request.getParameter("projectId");
		
		if(pid == null || pid =="" ){
//			return new JspView("redirect:/project/projectList");
			return new JspView("jsp.selectProjectMsg");
		}
		Integer projectId = Integer.parseInt(pid);
		List<ExcelTable> tableList = tableDao.findTablesByProjectId(projectId);
		/*Project project = projectDao.findProjectById(projectId);
		
		request.getServletContext().setAttribute("project", project);*/
		request.setAttribute("tableList", tableList);
		
		return null;
	}
	
	@At("/creatorTableList")
	@Ok("jsp:jsp.creatorTableList")
	public View creatorTableList(HttpServletRequest request) {
		String pid = request.getParameter("projectId");
		
		if(pid == null || pid =="" ){
//			return new JspView("redirect:/project/projectList");
			return new JspView("jsp.selectProjectMsg");
		}
		int userId = Integer.parseInt(request.getParameter("userId"));
		Integer projectId = Integer.parseInt(pid);
		ExcelTable excelTable = new ExcelTable();
		excelTable.setProjectId(projectId);
		excelTable.setUserId(userId);
		List<ExcelTable> tableList = tableDao.findTablesByUserIdAndProjectId(excelTable);
	
		request.setAttribute("tableList", tableList);
		
		return null;
	}
	
	@At("/joinTableList")
	@Ok("jsp:jsp.joinTableList")
	public View joinTableList(HttpServletRequest request) {
		String pid = request.getParameter("projectId");
		
		if(pid == null || pid =="" ){
//			return new JspView("redirect:/project/projectList");
			return new JspView("jsp.selectProjectMsg");
		}
		int userId = Integer.parseInt(request.getParameter("userId"));
		Integer projectId = Integer.parseInt(pid);
		TableRow tablerow = new TableRow();
		tablerow.setProjectId(projectId);
		tablerow.setUserId(userId);
		
		List<Integer> tableIdList = tableRowDao.findTableIdByUIdAndPId(tablerow);
		List<ExcelTable> tableList;
		if(tableIdList.size() == 0){
			tableList = null;
		}else{
			
			tableList = tableDao.findTableByTableIdList(tableIdList);
		}
		request.setAttribute("tableList", tableList);
		
		return null;
	}
	
	@At("/finishList")
	@Ok("jsp:jsp.finishList")
	public View finishList(HttpServletRequest request) {
		String pid = request.getParameter("projectId");
		if(pid == null || pid =="" ){
//			return new JspView("redirect:/project/projectList");
			return new JspView("jsp.selectProjectMsg");
		}
		
		
		int projectId = Integer.parseInt(pid);
	
		
		ExcelTable table = new ExcelTable();
		
		table.setProjectId(projectId);
		List<ExcelTable> tableList = tableDao.findFinishTable(table);
		
		request.setAttribute("tableList", tableList);
		return null;
	}
	
	/*@At("/changeStatuFinish")
	@Ok("jsp:jsp.finishList")
	public void changeStatuFinish(HttpServletRequest request) {
		String pid = request.getParameter("projectId");
		String tid = request.getParameter("tableId");
		
		int tableId = Integer.parseInt(tid);
		int projectId = Integer.parseInt(pid);
		tableDao.updateFinish(tableId);
		
		ExcelTable table = new ExcelTable();
		table.setId(tableId);
		table.setProjectId(projectId);
		List<ExcelTable> tableList = tableDao.findFinishTable(table);
		
		request.setAttribute("tableList", tableList);
		
	}*/
	
	@At("/changeStatuFinish")
	
	public void changeStatuFinish(HttpServletRequest request,HttpServletResponse response) {
		String pid = request.getParameter("projectId");
		String tid = request.getParameter("tableId");
		
		int tableId = Integer.parseInt(tid);
		int projectId = Integer.parseInt(pid);
		tableDao.updateFinish(tableId);
		
		
		
		
	}
	
	@At("/delete")
	@Ok("json")
	public Map deleteTable(HttpServletRequest request) {
		String tid = request.getParameter("tableId");
		
		Integer tableId = Integer.parseInt(tid);
		Map map = new HashMap();
		tableDao.deleteTable(tableId);
		tableColDao.deleteTableColByTableId(tableId);
		tableRowDao.deleteTableRowByTableId(tableId);
		mergeDao.deleteMergeColByTableId(tableId);
		mergeRowDao.deleteMergeRowByTableId(tableId);
		
		map.put("true", true);
		return map;
	}
	
	@At("/create2")
	@Ok("jsp:jsp.createTable2")
	public void createTable2(HttpServletRequest request) {
		List<User> users = userdao.findAllUser();
		request.setAttribute("users", users);
		
	}
	
	@At("/setEditor")
	@Ok("jsp:jsp.editor")
	public void setEditor(HttpServletRequest request) {
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		List<Integer> userIds = userProjectDao.findUserIdsByProjectId(projectId);
		List<User> users = userdao.findUserByIds(userIds);
		request.setAttribute("users", users);
		
	}
	@At("/setColEditor")
	@Ok("jsp:jsp.colEditor")
	public void setColEditor(HttpServletRequest request) {
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		List<Integer> userIds = userProjectDao.findUserIdsByProjectId(projectId);
		List<User> users = userdao.findUserByIds(userIds);
		request.setAttribute("users", users);
		
	}
	@At("/addTableCol")
	
	public void addTableCol(HttpServletRequest request) {
		int tableId = Integer.parseInt(request.getParameter("tableId"));
		int colEditor = Integer.parseInt(request.getParameter("colEditor"));
		String colName = request.getParameter("colName");
		TableCol tableCol = new TableCol();
		tableCol.setColName(colName);
		tableCol.setTableId(tableId);
		tableCol.setColEditor(colEditor);
		tableCol.setColType(0);
		tableColDao.addTableCol(tableCol);
		
	}
	
	@At("/addTableRow")
	
	public void addTableRow(HttpServletRequest request) {
		int tableId = Integer.parseInt(request.getParameter("tableId"));
		int rowEditor = Integer.parseInt(request.getParameter("rowEditor"));
		int projectId = Integer.parseInt(request.getParameter("projectId"));
		
		TableRow tableRow = new TableRow();
		tableRow.setProjectId(projectId);
		tableRow.setTableId(tableId);
		tableRow.setUserId(rowEditor);
		tableRowDao.addTableRow(tableRow);
		
	}
	
	@At("/mergeBoxCol")
	
	public void mergeBoxCol(HttpServletRequest request) {
		try{
			
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int colNum = Integer.parseInt(request.getParameter("colNum"));
			int rowNum = Integer.parseInt(request.getParameter("rowNum"));
			int colspan = Integer.parseInt(request.getParameter("colspan"));
			Merge merge = new Merge();
			merge.setTableId(tableId);
			merge.setColNum(colNum);
			merge.setRowNum(rowNum);
			merge.setColspan(colspan);
			Merge existMerge = mergeDao.findMergeByInfo(merge);
			if(existMerge == null){
				mergeDao.mergeBoxCol(merge);
			}else{
				mergeDao.updateMergeBoxCol(merge);
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@At("/deleteMergeCol")
	
	public void deleteMergeCol(HttpServletRequest request) {
		try{
			
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int colNum = Integer.parseInt(request.getParameter("colNum"));
			int rowNum = Integer.parseInt(request.getParameter("rowNum"));
			
			Merge merge = new Merge();
			merge.setTableId(tableId);
			merge.setColNum(colNum);
			merge.setRowNum(rowNum);
			mergeDao.deleteMergeCol(merge);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@At("/deleteMergeRow")
	
	public void deleteMergeRow(HttpServletRequest request) {
		try{
			
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int colNum = Integer.parseInt(request.getParameter("colNum"));
			int rowNum = Integer.parseInt(request.getParameter("rowNum"));
		
			MergeRow mergeRow = new MergeRow();
			mergeRow.setTableId(tableId);
			mergeRow.setColNum(colNum);
			mergeRow.setRowNum(rowNum);
			mergeRowDao.deleteMergeRow(mergeRow);
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@At("/addMergeBoxRow")
	
	public void addMergeBoxRow(HttpServletRequest request) {
		try{
			
			int tableId = Integer.parseInt(request.getParameter("tableId"));
			int colNum = Integer.parseInt(request.getParameter("colNum"));
			int rowNum = Integer.parseInt(request.getParameter("rowNum"));
			int rowspan = Integer.parseInt(request.getParameter("rowspan"));
			MergeRow mergeRow = new MergeRow();
			mergeRow.setTableId(tableId);
			mergeRow.setColNum(colNum);
			mergeRow.setRowNum(rowNum);
			mergeRow.setRowspan(rowspan);
			MergeRow existMerge = mergeRowDao.findMergeRowByInfo(mergeRow);
			if(existMerge == null){
				mergeRowDao.addMergeBoxRow(mergeRow);
			}else{
				mergeRowDao.updateMergeBoxRow(mergeRow);
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@At("/findMergeByTableId")
	
	public void findMergeByTableId(HttpServletRequest request,HttpServletResponse response) {
		try{
			String tid = request.getParameter("tableId");
			
			Integer tableId = Integer.parseInt(tid);
			List<Merge> list = null;
			list = mergeDao.findMergeByTableId(tableId);
			
			String jsonString = JSON.toJSONString(list);
			System.out.println(list.toString());
			response.getWriter().print(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	@At("/findMergeRowByTableId")
	
	public void findMergeRowByTableId(HttpServletRequest request,HttpServletResponse response) {
		try{
			String tid = request.getParameter("tableId");
			
			Integer tableId = Integer.parseInt(tid);
			List<MergeRow> list = null;
			list = mergeRowDao.findMergeRowByTableId(tableId);
			
			String jsonString = JSON.toJSONString(list);
			System.out.println(list.toString());
			response.getWriter().print(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	

}
